using UnityEngine;

// 挂载到玩家身上，实现简单相机跟随效果
public class CameraWork : MonoBehaviour
{
    [Tooltip("与目标的距离")]
    [SerializeField] private float distance = 7f;
    [SerializeField] private float height = 3f;
    [SerializeField] private Vector3 centerOffset = Vector3.zero;
    [SerializeField] private bool followOnStart = false;
    [SerializeField] private float smoothSpeed = 0.125f;

    Transform cameraTransform;
    bool isFollowing;
    Vector3 cameraOffset = Vector3.zero;

    private void Start()
    {
        if (followOnStart)
        {
            OnStartFollowing();
        }
    }
    private void LateUpdate()
    {
        if (cameraTransform == null && isFollowing)
        {
            OnStartFollowing();
        }

        if (isFollowing)
        {
            Follow();
        }
    }

    public void OnStartFollowing()
    {
        cameraTransform = Camera.main.transform;
        isFollowing = true;
        Cut();
    }

    private void Follow()
    {
        cameraOffset.z = -distance;
        cameraOffset.y = height;
        // 更新相机位置
        cameraTransform.position = Vector3.Lerp(cameraTransform.position, this.transform.position + this.transform.TransformVector(cameraOffset), smoothSpeed * Time.deltaTime);

        cameraTransform.LookAt(this.transform.position + centerOffset);
    }

    private void Cut()
    {
        cameraOffset.z = -distance;
        cameraOffset.y = height;

        cameraTransform.position = this.transform.position + this.transform.TransformVector(cameraOffset);

        cameraTransform.LookAt(this.transform.position + centerOffset);
    }
}
